//创建用户相关的
import {defineStore} from 'pinia'
//引入路由(常量路由)
import {asyncRouteAdmin, asyncRouteVisitor, constantRoute} from '@/router/router'
import {apiGet} from "@/utils/api.ts";
import router from "@/router";
import {sessionStorage} from "@/utils/storage.ts";

export const useUserStore = defineStore('user', {
    state: () => {
        return {
            username: '',
            nickname: '',
            avatar: '',
            role: 0,
            accountBalance: 0,
            freezeMoney: 0,
            id: 0,
            menuRoutes: constantRoute,
        }
    },
    //异步修改状态
    actions: {
        //请求用户个人信息
        async userInfo() {
            const {data} = await apiGet('/trainers/getById');
            //由于pinia|vuex存储数据其实利用js对象
            this.username = data.account;
            this.nickname = data.name;
            this.avatar = data.avatar;
            this.role = data.role || 2;
            this.accountBalance = data.accountBalance;
            this.freezeMoney = data.freezeMoney;
            this.id = data.trainerId;
            if (this.role === 1) {
                this.menuRoutes = [...constantRoute, ...asyncRouteAdmin]
            } else if (this.role === 2) {
                this.menuRoutes = [...constantRoute, ...asyncRouteVisitor]
            }
            this.menuRoutes.forEach((route: any) => {
                router.addRoute(route)
            })
            return 'ok'
        },
        //退出登录
        async userLogout() {
            sessionStorage.remove('ADMIN_TOKEN');
            this.username = ''
            this.nickname = ''
            this.role = 0
            this.avatar = ''
            this.accountBalance = 0
            this.freezeMoney = 0
            this.id = 0
            this.menuRoutes = constantRoute
            return 'ok'
        },
        //模拟菜单数据
        getMenu() {
            return this.menuRoutes
        },
    },
    getters:
        {}
    ,
})
